package com.huawei.codearts.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

@Configuration
public class JedisConfig {

    private volatile static JedisPool jedisPool = null;

    @Value("${redis.host}")
    private String HOST;
    @Value("${redis.port}")
    private int PORT;
    @Value("${redis.timeout}")
    private int TIMEOUT;
    @Value("${redis.auth}")
    private String AUTH;
    @Value("${redis.select}")
    private int SELECT;
    @Value("${redis.jedis.pool.max-active}")
    private int MAX_TOTAL;  // 最大连接数
    @Value("${redis.jedis.pool.max-idle}")
    private int MAX_IDLE;  // 连接池中的最大空闲连接
    @Value("${redis.jedis.pool.min-idle}")
    private int MIN_IDLE;  // 连接池中的最小空闲连接
    @Value("${redis.jedis.pool.max-wait}")
    private int MAX_WAIT;  // 连接池最大阻塞等待时间 ms

    @Bean
    public JedisPool getJedisPoolInstance() {
        // 使用双重检查创建单例
        if(null == jedisPool) {
            synchronized (JedisConfig.class) {
                if(null == jedisPool) {
                    //配置连接池
                    JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
                    //最大连接
                    jedisPoolConfig.setMaxTotal(MAX_TOTAL);
                    //最大空闲连接
                    jedisPoolConfig.setMaxIdle(MAX_IDLE);
                    //最小空闲连接
                    jedisPoolConfig.setMinIdle(MIN_IDLE);
                    //最长等待时间,ms
                    jedisPoolConfig.setMaxWaitMillis(MAX_WAIT);
                    jedisPoolConfig.setTestOnBorrow(true);
                    if (AUTH == null || AUTH.isEmpty()) {
                        jedisPool = new JedisPool(jedisPoolConfig, HOST, PORT, TIMEOUT);
                    } else {
                        jedisPool = new JedisPool(jedisPoolConfig, HOST, PORT, TIMEOUT, AUTH, SELECT);
                    }
                }
            }
        }
        return jedisPool;
    }

}
